package model

import (
	"gpt-api/framework/db"
)

type MemberImage struct {
	db.BaseModel
	UserID   uint64 `json:"user_id" gorm:"column:user_id;type:int;not null;comment:用户ID"`
	MemberID uint   `json:"member_id" gorm:"column:member_id;type:int;not null;comment:成员ID"`
	ImageUrl string `json:"image_url" gorm:"column:image_url;type:varchar(255);default:'';comment:图片地址"`
	Type     int8   `json:"type" gorm:"column:type;type:int;default:1;comment:图片类型,1=图片,2=视频"`
}

func (MemberImage) TableName() string {
	return "member_image"
}

// 根据ids批量查询图片信息
func (m MemberImage) GetMemberImagesByIds(database *db.DB, ids []uint64) ([]MemberImage, error) {
	var images []MemberImage
	err := database.Where("id IN (?)", ids).Find(&images).Error
	if err != nil {
		return nil, err
	}
	return images, nil
}

// 创建图片
func (m MemberImage) Create(database *db.DB) (uint64, error) {
	err := database.Create(&m).Error
	if err != nil {
		return 0, err
	}

	return m.ID, nil
}

// 根据member_id获取图片,分页
func (m MemberImage) GetMemberImages(database *db.DB, memberId uint64, imageType uint8, page, pageSize int) ([]MemberImage, error) {
	var images []MemberImage
	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 {
		pageSize = 10
	}
	init := database.Model(&MemberImage{})
	if memberId > 0 {
		init.Where("member_id = ?", memberId)
	}
	if imageType > 0 {
		init.Where("type = ?", imageType)
	}
	err := init.Offset((page - 1) * pageSize).Order("id desc").Limit(pageSize).Find(&images).Error
	if err != nil {
		return nil, err
	}
	return images, nil
}

// 根据member_id统计所有图片数量
func (m MemberImage) CountMemberImages(database *db.DB, memberId uint64) (int64, error) {
	var count int64
	err := database.Model(&MemberImage{}).Where("member_id = ?", memberId).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

// 根据id批量删除图片
func (m MemberImage) DeleteMemberImages(database *db.DB, ids []uint64) error {
	err := database.Where("id IN (?)", ids).Delete(&MemberImage{}).Error
	if err != nil {
		return err
	}
	return nil
}

// 根据path查询图片
func (m MemberImage) GetMemberImageByPath(database *db.DB, path string) (MemberImage, error) {
	var image MemberImage
	err := database.Model(&MemberImage{}).Where("image_url = ?", path).First(&image).Error
	if err != nil {
		return MemberImage{}, err
	}
	return image, nil
}
